<template>
  <div>
	<el-row type="flex" justify="center" class="page-header" style="margin-bottom: 30px;">
	        <el-col :span="24" class="text-center">
	            <div class="title-wrapper">
	            <i class="el-icon-search el-icon--large"></i>
	            <h1 class="main-title">消防栓信息管理系统</h1>
	            <p class="sub-title">记录每一次巡检，呵护每一台设备，消防栓的完好，藏着对生命与安全的郑重承诺</p>
	            </div>
	        </el-col>
	</el-row>
    <el-dialog
      v-model="dialogVisible"
      title="详情"
      width="70%">
      <--<Meiyibiao/>
    </el-dialog>
    <el-dialog
      v-model="dialogVisible1"
      title="编辑"
      width="70%"
	  style="z-index: 9999 !important; position: fixed !important; top: 100px !important;">
      <el-form :model="ruleForm" :rules="rules" ref="editRuleFormRef" label-width="100px" class="demo-ruleForm">
        <el-row>
          <el-col :span="12">
            <el-form-item label="编号" prop="hydrantId">
              <el-input v-model="ruleForm.hydrantId" placeholder="请输入编号"></el-input>
            </el-form-item>
            <el-form-item label="地点" prop="locationId">
              <el-input v-model="ruleForm.locationId" placeholder="请输入地点"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上次检查日期" prop="lastInspectionDate">
              <el-date-picker
                v-model="ruleForm.lastInspectionDate"
                type="date"
                placeholder="选择日期"
                style="width: 100%;">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="下次检查日期" prop="nextInspectionDate">
              <el-date-picker
                v-model="ruleForm.nextInspectionDate"
                type="date"
                placeholder="选择日期"
                style="width: 100%;">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-button @click="updateSubmit()">确定</el-button>
      </el-form>
    </el-dialog>
    <!-- 新增 -->
    <el-dialog
      v-model="dialogVisible2"
      title="新增"
      width="70%">
      <el-form :model="addForm" :rules="rules" ref="addRuleFormRef" label-width="100px" class="demo-ruleForm">
        <el-row>
          <el-col :span="12">
            <el-form-item label="编号" prop="hydrantId">
              <el-input v-model="addForm.hydrantId" placeholder="请输入编号"></el-input>
            </el-form-item>
            <el-form-item label="地点" prop="locationId">
              <el-input v-model="addForm.locationId" placeholder="请输入地点"></el-input>
            </el-form-item>
            <el-form-item label="检查人" prop="locationId">
              <el-input v-model="addForm.inspector" placeholder="请输入检查人"></el-input>
            </el-form-item>
            <el-select v-model="addForm.isQualified" placeholder="请选择分类" style="width: 100%;">
              <el-option label="是否合格" value=""></el-option>
              <el-option label="true" value="true"></el-option>
              <el-option label="false" value="false"></el-option>
            </el-select>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上次检查日期" prop="lastInspectionDate">
              <el-date-picker
                v-model="addForm.lastInspectionDate"
                type="date"
                placeholder="选择日期"
                style="width: 100%;">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="下次检查日期" prop="nextInspectionDate">
              <el-date-picker
                v-model="addForm.nextInspectionDate"
                type="date"
                placeholder="选择日期"
                style="width: 100%;">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-button @click="addSubmit()">确定</el-button>
      </el-form>
    </el-dialog>
    <el-row>
      <el-row :gutter="20" style="width: 100%;">
        <el-col :span="18" :offset="0">
          <!-- <el-input placeholder="状态查询" v-model="searchQuery" style="width: 50%;"></el-input> -->
          <el-select v-model="selectedCategory" placeholder="请选择分类" style="width: 100%;">
            <el-option label="是否合格" value=""></el-option>
            <el-option label="true" value="true"></el-option>
            <el-option label="false" value="false"></el-option>
          </el-select>
        </el-col>
        <el-col :span="6" :offset="0" class="text-right">
          <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
          <el-button type="primary" icon="el-icon-plus" @click="openDetails2()">添加</el-button>
        </el-col>
      </el-row>
      <el-table :data="tableData.slice((currentPage-1)*pageSize, currentPage*pageSize)" border style="width: 100%"
                height="450" :row-class-name="tableRowClassName">
        <el-table-column fixed prop="hydrantId" label="编号" width="150" align="center">
        </el-table-column>
        <el-table-column prop="locationId" label="地点" width="150" align="center">
        </el-table-column>
        <el-table-column prop="lastInspectionDate" label="上次检查日期" width="150" align="center">
        </el-table-column>
        <el-table-column prop="nextInspectionDate" label="下次检查日期" width="150" align="center">
        </el-table-column>
        <el-table-column prop="inspector" label="检查人" align="center">
        </el-table-column>
        <el-table-column prop="isQualified" label="处理状态" width="140" align="center">
          <template #default="{ row, $index }">
            <el-select v-model="row.isQualified" @change="updateRowStatus($index, row)" placeholder="处理状态">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="scope"> <!-- 注意：Vue3 建议用 #default 替代 slot-scope -->
            <!-- 编辑按钮：改为 primary 类型（蓝色 -->
            <el-button type="primary" size="small" @click="openDetails1(scope.row)">编辑</el-button>
            <!-- 删除按钮：改为 danger 类型（红色 -->
            <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-row type="flex">
        <el-col :push=5>
          <!-- 分页 -->
          <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
                         :page-sizes="[5,10,20,50]" :page-size="pageSize" :total="tableData.length"
                         layout="total, sizes, prev, pager, next, jumper">
          </el-pagination>
        </el-col>
      </el-row>
    </el-row>
  </div>
</template>


<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import Meiyibiao from './Meiyibiao.vue';
import { post } from '@/utils/axios';
import { get } from '@/utils/axios';

const options = [
  { value: 'true', label: 'true' },
  { value: 'false', label: 'false' }
];

const dialogVisible = ref(false);
const dialogVisible1 = ref(false);
const dialogVisible2 = ref(false);
const selectedCategory = ref('');
const currentPage = ref(1);
const pageSize = ref(5);
const tableData = ref([]);

// 编辑表单的 ref
const editRuleFormRef = ref(); 
// 新增表单的 ref
const addRuleFormRef = ref(null); 

const ruleForm = reactive({
  hydrantId: '',
  locationId: '',
  lastInspectionDate: '',
  nextInspectionDate: '',
  inspector: '',
  isQualified: '',
});
const addForm = reactive({
  hydrantId: '',
  locationId: '',
  lastInspectionDate: '',
  nextInspectionDate: '',
  inspector: '',
  isQualified: '',
});

const ruleFormRef = ref();

function changeDate(date) {
  if (!date) return '';
  const d = new Date(date);
  const y = d.getFullYear();
  const m = String(d.getMonth() + 1).padStart(2, '0');
  const day = String(d.getDate()).padStart(2, '0');
  return `${y}-${m}-${day}`;
}

function updateRowStatus(index, row) {
  const data = {
    hydrantId: row.hydrantId,
    locationId: row.locationId,
    lastInspectionDate: row.lastInspectionDate,
    nextInspectionDate: row.nextInspectionDate,
    inspector: row.inspector,
    isQualified: row.isQualified
  };
  post('/sc/firehydrant/updateById', data, (res) => {
    if (res.status === 1) {
      ElMessage.success('修改成功！');
    } else {
      ElMessage.error('未查询到数据，请重新查询');
    }
  });
}

function tableRowClassName({ row }) {
  const statusColorMap = {
    '0': 'red-row',
    '1': 'green-row'
  };
  return statusColorMap[row.isQualified] || '';
}

function openDetails(row) {
  dialogVisible.value = true;
}
function openDetails1(row) {
  console.log('编辑方法被调用，赋值前 dialogVisible1:', dialogVisible1.value); // 应该是 false
    dialogVisible1.value = true;
    console.log('编辑方法被调用，赋值后 dialogVisible1:', dialogVisible1.value);
  ruleForm.hydrantId = row.hydrantId;
  ruleForm.locationId = row.locationId;
  ruleForm.lastInspectionDate = row.lastInspectionDate;
  ruleForm.nextInspectionDate = row.nextInspectionDate;
  ruleForm.inspector = row.inspector;
  ruleForm.isQualified = row.isQualified;
}
function openDetails2() {
  dialogVisible2.value = true;
  // 新增弹窗
}

function handleSizeChange(val) {
  pageSize.value = val;
}
function handleCurrentChange(val) {
  currentPage.value = val;
}

function updateSubmit() {
  // 触发编辑表单的校验
  editRuleFormRef.value.validate((valid) => {
    if (!valid) return; // 校验失败，不发请求

    // 日期格式转换（如果 el-date-picker 未设 value-format）
    if (typeof ruleForm.lastInspectionDate !== 'string')
      ruleForm.lastInspectionDate = changeDate(ruleForm.lastInspectionDate);
    if (typeof ruleForm.nextInspectionDate !== 'string')
      ruleForm.nextInspectionDate = changeDate(ruleForm.nextInspectionDate);

    // isQualified 字符串转布尔（后端若需布尔值）
    ruleForm.isQualified = ruleForm.isQualified === 'true';

    // 调用更新接口
    post('/sc/firehydrant/updateById', ruleForm, (res) => {
      if (res.status === 1) {
        ElMessage.success('修改成功！');
        getAllData(); // 刷新表格
        dialogVisible1.value = false; // 关闭弹窗
      } else {
        ElMessage.error('修改失败，请检查参数');
      }
    });
  });
}

function addSubmit() {
  
  if (!addRuleFormRef.value) {
      ElMessage.error('表单未正确初始化');
      return;
    }
  
  // 触发新增表单的校验
  addRuleFormRef.value.validate((valid) => {
    if (!valid) return; // 校验失败，不发请求

    // 日期格式转换（如果 el-date-picker 未设 value-format）
    if (typeof addForm.lastInspectionDate !== 'string')
      addForm.lastInspectionDate = changeDate(addForm.lastInspectionDate);
    if (typeof addForm.nextInspectionDate !== 'string')
      addForm.nextInspectionDate = changeDate(addForm.nextInspectionDate);

    // isQualified 字符串转布尔（后端若需布尔值）
    addForm.isQualified = addForm.isQualified === 'true';

    // 调用新增接口
    post('/sc/firehydrant/add', addForm, (res) => {
      if (res.status === 1) {
        ElMessage.success('新增成功！');
        getAllData(); // 刷新表格
        dialogVisible2.value = false; // 关闭弹窗
      } else {
        ElMessage.error('新增失败，请检查参数');
      }
    });
  });
}

// 1. 安装axios：npm install axios
// 2. 引入并使用
import axios from 'axios';

function handleSearch() {
  const queryParams = { 
    isQualified: selectedCategory.value  // 扁平参数，无嵌套
  };

  // 标准Axios调用：params直接传递，不会加多余前缀
  axios.get('http://172.16.1.138:8088/sc/firehydrant/byQualified', { 
    params: queryParams,
    withCredentials: true // 若后端允许Cookie，需加这行（与后端allowCredentials对应）
  })
  .then(res => {
    if (res.data.status === 1) {
      ElMessage.success('查询成功！');
      tableData.value = res.data.data;
    } else {
      ElMessage.error('未查询到数据');
    }
  })
  .catch(error => {
    ElMessage.error('请求失败：' + error.message);
    // 打印实际请求URL，确认是否有特殊字符
    console.log('实际请求URL：', error.config.url);
  });
}


function handleDelete(row) {
  post('/sc/firehydrant/deleteById', { hydrantId: row.hydrantId }, (res) => {
    if (res.status === 1) {
      ElMessage.success('删除成功！');
      getAllData();
    } else {
      ElMessage.error('未查询到数据，请重新查询');
    }
  });
}

function getAllData() {
  post('/sc/firehydrant/getAll', {}, (res) => {
    if (res.status === 1) {
      tableData.value = res.data;
    } else {
      ElMessage.error('未查询到数据，请重新查询');
    }
  });
}

onMounted(() => {
  getAllData();
});
</script>

<style scoped>
/* 标题样式 */
.page-header {
  padding: 10px 0;
  border-bottom: 1px solid #e5e7eb;
}

.title-wrapper {
  display: inline-flex;
  flex-direction: column;
  align-items:flex-start;
  gap: 8px;
}

.main-title {
  font-size: 28px;
  font-weight: 600;
  color: #1f2937;
  margin: 0;
  display: flex;
  align-items: center;
  gap: 12px;
}

.sub-title {
  font-size: 16px;
  color: #6b7280;
  margin: 0;
}

.el-icon--large {
  font-size: 28px;
  color: #409eff;
}
.el-table .red-row {
  background-color: #ffdddd; /* 浅红色 */
}

.el-table .yellow-row {
  background-color: #ffffcc; /* 浅黄色 */
}

.el-table .green-row {
  background-color: #ddffdd; /* 浅绿色 */
}

.text-right {
  display: flex;
  justify-content: flex-end;
  align-items: center; /* 如果需要垂直居中 */
}

div {
  width: auto;
}
</style>
